package training.sample.app.web;

import java.util.Locale;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import training.sample.app.domain.UserAccount;
import training.sample.app.security.ApplicationUserDetails;
import training.sample.app.service.UserService;

@Controller
@RequestMapping("/profile")
public class ProfileController {

	@Autowired
	private UserService userService;
	
	@PreAuthorize("isFullyAuthenticated() and hasAnyRole('ROLE_ADMIN','ROLE_USER')")	
	@RequestMapping(value = { "", "/" }, method = RequestMethod.GET)
	public String showUserProfile(
			Authentication authentication,
			HttpSession session, Model model) {

		ApplicationUserDetails appUser = (ApplicationUserDetails) authentication.getPrincipal();
		
		Locale locale = LocaleContextHolder.getLocale();
	    String language = locale.getLanguage();
	    
	    System.out.println("language="+language);
	    
		UserAccount user = appUser.getAccount();
		session.setAttribute("user", user);
		
		return "profile";
	}
	
	@PreAuthorize("isFullyAuthenticated()")	
	@RequestMapping(value = "/{userId}", method = RequestMethod.GET)
	public ModelAndView showUserProfileByID(
			Authentication authentication,
			@PathVariable String userId,
			@PathVariable("userId") UserAccount userModelTest,
			HttpSession session, Model model) {

		Locale locale = LocaleContextHolder.getLocale();
	    String language = locale.getLanguage();
	    
	    System.out.println("language="+language);
	    
		ModelAndView mav = new ModelAndView();
		mav.setViewName("profile");
		mav.addObject("userModelTest", userModelTest);
		
		Object userObject = session.getAttribute("user");
		if ((userObject != null) && (userObject instanceof UserAccount)) {
			UserAccount user = (UserAccount) userObject;
			
			mav.addObject("user.name", user.getName());
			System.out.println("Found an user with ID: " + user.getUserId());
		}
		
		return mav;
	}
}